package cn.apthink.solon;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Action;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

import lombok.extern.slf4j.Slf4j;

@Slf4j
//定义方法调用计时拦截器
@Component(index = -98)
public class CallTimerInterceptor implements RouterInterceptor {
	@Override
	public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
		CallTimer anno = null;
		Action action = ctx.action();
		if (action != null) {
			anno = action.method().getAnnotation(CallTimer.class);
		}
		if (anno == null) {
			// 如果没有注解
			chain.doIntercept(ctx, mainHandler);
		} else {
			// 1.开始计时
			long start = System.currentTimeMillis();
			try {
				chain.doIntercept(ctx, mainHandler);
			} finally {
				// 2.获得接口响应时长
				long timespan = System.currentTimeMillis() - start;
				// 3.记日志
				log.info("=>CallTimerInterceptor: "+action.method().getName()+"用时" + timespan);
			}
		}
	}
}
